package cn.topcode.unicorn.utils;

import org.springframework.context.ApplicationEvent;
import java.io.Serializable;

public class DistEvent extends ApplicationEvent {

	private static final String[] IGNORE_PROP_NAME_ARR = {"source", "timestamp", "time", "type", "playload"};

	private static final String[] INCLUDE_PROP_NAME_ARR = {"type", "playload", "time"};

	private String type;

	private String playload;

	private long time = System.currentTimeMillis();

	public DistEvent() {
		super(new Serializable() {});
	}

	public DistEvent(String type) {
		super(new Serializable() {});
		this.type = type;
	}

	public <T extends DistEvent> T unpack(Class<T> clazz) {
		if(StringUtil.isNotBlank(playload)) {
			T t = (T) JsonUtil.parse(playload, clazz);
			t.setType(this.getType());
			t.setPlayload(this.playload);
			t.setTime(this.getTimestamp());
			return t;
		}
		return null;
	}

	void pack() {
		playload = JsonUtil.toJsonIgnoreProp(this, IGNORE_PROP_NAME_ARR);
	}

	String toJson() {
		return JsonUtil.toJsonIncludeProp(this, INCLUDE_PROP_NAME_ARR);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getPlayload() {
		return playload;
	}

	public void setPlayload(String playload) {
		this.playload = playload;
	}

	public long getTime() {
		return time;
	}

	public void setTime(long time) {
		this.time = time;
	}
}
